<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card shadow="hover">
      <el-alert
        title="注意：只允许为第三级分类设置相关参数！"
        type="warning"
        :closable="false"
        show-icon>
      </el-alert>

      <el-row class="el-row-selector">
        <el-col>
          <span>选择商品分类：</span>
          <el-cascader
            v-model="selectedValueList"
            :options="cateList"
            :props="cascaderProps"
            @change="handleChange"
            style="width: 300px"
            clearable>
          </el-cascader>
        </el-col>
      </el-row>

      <el-tabs v-model="activeName" @tab-click="handleTabClick">

        <el-tab-pane label="动态参数" name="many">
          <el-button :disabled="calActive" type="primary" @click="addDialogVisible = true">添加参数</el-button>

          <el-table

            :data="manyTableData"
            border 
            class="cate-params-table"
            height="500"
            style="width: 100%"
            
            >
            <el-table-column type="expand" >
            
            <template slot-scope="scope">
                <el-tag closable v-for="(item, i) in scope.row.attr_vals" :key="i" @close="handleTagClosed(i, scope.row)">{{item}}</el-tag>

                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>



              </template>

            </el-table-column>
          <el-table-column type="index" label="#"></el-table-column>

            <el-table-column
              prop="attr_name"
              label="参数名称"
              width="500px">
            </el-table-column>
            <el-table-column
              label="操作"
              >
        
          <template slot-scope="scope">
            <el-button
              type="primary"
              size="mini"
              round
              icon="el-icon-edit"
              @click="showEditDialog(scope.row)"
              >编辑</el-button
            >
            <el-button
              type="danger"
              size="mini"
              round
              icon="el-icon-delete"
              @click="showDeleteDialog(scope.row)"
              >删除</el-button>
        </template>
            </el-table-column>
          </el-table>

        </el-tab-pane>

        <el-tab-pane label="静态属性" name="only">
          <el-button :disabled="calActive" type="primary" @click="addDialogVisible = true">添加属性</el-button>

            <el-table
            :data="onlyTableData"
            style="width: 100%" border class="cate-params-table">
            <el-table-column type="expand" >

              <template slot-scope="scope">
                <el-tag closable v-for="(item, i) in scope.row.attr_vals" :key="i" @close="handleTagClosed(i, scope.row)">{{item}}</el-tag>

              
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              

              </template>
            
            </el-table-column>
          <el-table-column type="index" label="#"></el-table-column>

            <el-table-column
              prop="attr_name"
              label="属性名称"
              width="500px">
            </el-table-column>
            <el-table-column
              label="操作"
              >
              
          <template slot-scope="scope">
            <el-button
              type="primary"
              size="mini"
              round
              icon="el-icon-edit"
              @click="showEditDialog(scope.row)"
              >编辑</el-button
            >
            <el-button
              type="danger"
              size="mini"
              round
              icon="el-icon-delete"
              @click="showDeleteDialog(scope.row)"
              >删除</el-button>
        </template>
            </el-table-column>
          </el-table>

        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 添加动态参数与添加静态属性公用的对话框 -->
    <el-dialog :title="'添加'+calTitle" :visible.sync="addDialogVisible" width="40%" @close="handleAddCancel()">

      <el-form :model="addParamsForm" :rules="addParamsRules" ref="addParamsRef" label-width="100px">
        <el-form-item :label="calTitle" prop="attr_name">
          <el-input v-model="addParamsForm.attr_name"></el-input>
        </el-form-item>
        <el-form-item :label="calTitle1">
          <el-input v-model="addParamsForm.attr_vals" placeholder="用空格将多个描述分开"></el-input>
        </el-form-item>
      </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addParams()">确 定</el-button>
        </span>
    </el-dialog>


    <!-- 编辑动态参数与添加静态属性公用的对话框 -->
    <el-dialog :title="'编辑'+calTitle" :visible.sync="editDialogVisible" width="40%" @close="handleEditCancel()">

      <el-form :model="editParamsForm" :rules="editParamsRules" ref="editParamsRef" label-width="100px">
        <el-form-item :label="calTitle" prop="attr_name">
          <el-input v-model="editParamsForm.attr_name"></el-input>
        </el-form-item>
        <el-form-item :label="calTitle1">
          <el-input v-model="editParamsForm.attr_vals"></el-input>
        </el-form-item>
      </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editParams()">确 定</el-button>
        </span>
    </el-dialog>


    <!-- 删除动态参数与添加静态属性公用的对话框 -->
    <el-dialog :title="'删除'+calTitle" :visible.sync="deleteDialogVisible" width="40%" @close="handleDeleteCancel()">

      <el-form :model="deleteParamsForm" ref="deleteParamsRef" label-width="100px">
        <el-form-item :label="calTitle" prop="attr_name">
          <el-input disabled v-model="deleteParamsForm.attr_name"></el-input>
        </el-form-item>
        <el-form-item :label="calTitle1">
          <el-input disabled v-model="deleteParamsForm.attr_vals"></el-input>
        </el-form-item>
      </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="deleteDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="deleteParams()">确 定</el-button>
        </span>
    </el-dialog>

  </div>
</template>

<script>
export default {
  created(){
    this.getGoodsCateList();
  },
  data(){
    return{
      cateList:[],
      selectedValueList:[],
      cascaderProps: {
        value: "cat_id",
        label: "cat_name",
        children: "children",
        expandTrigger: 'hover'
      },
      activeName:'many',
      manyTableData:[],
      onlyTableData:[],
      addDialogVisible:false,
      addParamsForm:{},

      addParamsRules:{
        attr_name:[
          {required: true, message: "请输入角色名称", trigger: "blur"}
        ]
      },
      editDialogVisible:false,
      editParamsForm:{},
      editParamsRules:{
        attr_name:[
          {required: true, message: "请输入角色名称", trigger: "blur"}
        ]
      },
      deleteDialogVisible:false,
      deleteParamsForm:{},
      deleteParamsRules:{
        attr_name:[
          {required: true, message: "请输入角色名称", trigger: "blur"}
        ]
      },
      // 不需要，直接展开
      // expandTagList:[],
      // 删去，不能这样定义，否则共享一个会导致冲突，在循环的时候单独定义属性
      // inputVisible:false,
      // inputValue:''

    }
  },
  methods:{
    async getGoodsCateList(){
      const {data:res} = await this.$http.get('categories');
      if(res.meta.status !== 200) return this.$message.error("获取商品分类信息失败");
      this.cateList = res.data;
      // console.log(this.cateList);
    },
    handleChange(){
      // console.log(this.selectedValueList);
      this.getParamsData();

    },
    handleTabClick(){
      // console.log(this.activeName);
      this.getParamsData();
    },

    // 根据不同的入参获取分类参数和静态属性的方法
    async getParamsData(){
      if(this.selectedValueList.length !== 3){
        this.selectedValueList = [];
        this.manyTableData = [];
        this.onlyTableData = [];
        return;
      }
      const {data:res} = await this.$http.get(`categories/${this.calculateId}/attributes`, {params:{sel: this.activeName}});
      if(res.meta.status !== 200) return this.$message.error("获取参数列表失败");
      console.log(res.data);
      if(this.activeName === 'many'){
        this.manyTableData = res.data;
      }else{
        this.onlyTableData = res.data;
      }
      // console.log(res.data);
      res.data.forEach(item => {
          item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : [];
          // 弹幕牛皮操作！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！
          this.$set(item, 'inputVisible', false);
          this.$set(item, 'inputValue', '');
          // item.inputVisible = false
          // item.inputValue = ''
      });
      // console.log(res.data);
    },

    handleAddCancel(){
      this.addParamsForm = {};
      this.$refs.addParamsRef.resetFields();
    },
    addParams(){
      this.$refs.addParamsRef.validate(async valid => {
        if(!valid) return this.$message.error("添加信息校验失败");
        const {data:res} = await this.$http.post(`categories/${this.calculateId}/attributes`, 
        {attr_name:this.addParamsForm.attr_name, attr_sel: this.activeName, attr_vals:this.addParamsForm.attr_vals});

        if(res.meta.status !== 201) return this.$message.error("添加参数失败");
        this.getParamsData();
        this.addDialogVisible = false;
        this.$message.success("添加参数成功");
      })
    },
    handleEditCancel(){
      this.editParamsForm = {};
      this.$refs.editParamsRef.resetFields();
    },
    // 根据传过来的ID查询参数
    async showEditDialog(param){
      this.editDialogVisible = true;
      const {data:res} = await this.$http.get(`categories/${param.cat_id}/attributes/${param.attr_id}`);
       if(res.meta.status !== 200) return this.$message.error("参数查询失败");
      // console.log(res);
      this.editParamsForm = res.data;
    },
    editParams(){
      this.$refs.editParamsRef.validate(async valid => {
        if(!valid) return this.$message.error("编辑参数校验失败");
        const {data:res} = await this.$http.put(`categories/${this.editParamsForm.cat_id}/attributes/${this.editParamsForm.attr_id}`, 
        {attr_name:this.editParamsForm.attr_name, attr_sel:this.activeName, attr_vals:this.editParamsForm.attr_vals});

        if(res.meta.status !== 200) return this.$message.error("编辑参数失败");
        this.getParamsData();
        this.editDialogVisible = false;
        this.$message.success("编辑参数成功");
      })
    },
    handleDeleteCancel(){

    },
    async deleteParams(){
      const {data:res} = await this.$http.delete(`categories/${this.deleteParamsForm.cat_id}/attributes/${this.deleteParamsForm.attr_id}`);
      if(res.meta.status !== 200) return this.$message.error("参数删除失败");
      this.getParamsData();
      this.deleteDialogVisible = false;
      this.$message.success("参数删除成功");
    },

    async showDeleteDialog(param){
      this.deleteDialogVisible = true;
      const {data:res} = await this.$http.get(`categories/${param.cat_id}/attributes/${param.attr_id}`);
      if(res.meta.status !== 200) return this.$message.error("参数查询失败");
      // console.log(res);
      this.deleteParamsForm = res.data;
    },
    // 文本框失去焦点或者按下了Enter会触发的函数
    async handleInputConfirm(row){
      // 输入不合法的值，如空字符
      if(row.inputValue.trim().length === 0){
        row.inputValue = '';
        row.inputVisible = false;
        return;
      }
      // 输入非空字符，后续处理
      // 先把符合要求的值存入数据库
      this.saveSetParams(row, 1);
      // 然后我们重置输入框，重新显示button
      row.attr_vals.push(row.inputValue.trim());
      row.inputValue = '';
      row.inputVisible = false;

    },
    // 点击按钮触发的函数
    showInput(row){
      row.inputVisible = true;
      this.$nextTick(_ => {
          this.$refs.saveTagInput.$refs.input.focus();
      });
    },

    async handleTagClosed(i, row){

      const res = await this.$confirm('确定删除该描述？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(error => error);
      if(res !== 'confirm'){
        return this.$message.info('取消了删除');
      }

      row.attr_vals.splice(i, 1);
      this.saveSetParams(row, 0);
    },

    async saveSetParams(row, type){
      const {data:res} = await this.$http.put(`categories/${this.calculateId}/attributes/${row.attr_id}`, {
        attr_name: row.attr_name,
        attr_sel: row.attr_sel,
        attr_vals: row.attr_vals.join(' ')
      });

      if(res.meta.status !== 200) return this.$message.error("描述加入失败");
      if(type){
        this.$message.success("描述加入成功");
      }else{
        this.$message.error("描述删除成功");
      }
    }
  },
  computed:{
    calActive(){
      return this.selectedValueList.length === 3 ? false : true;
    },
    calculateId(){
      return this.selectedValueList.length === 3 ? this.selectedValueList[2] : null;
    },
    calTitle(){
      return this.activeName === 'many' ? '动态参数：' : '静态属性：';
    },
    calTitle1(){
      return this.activeName === 'many' ? '参数描述：' : '属性描述：';
    }
  }
 };
</script>

<style lang="less" scoped>
.el-row-selector{
  margin:20px 0;
}

.cate-params-table{
  margin:20px 0;
}

.el-tag{
  margin:0 10px;
}

.input-new-tag{
  margin:0 10px;
  width:120px;
}

.button-new-tag{
  margin:0 10px;
}

</style>
